package com.deYang.app.ljodfh.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.deYang.app.ljodfh.R;
import com.deYang.app.ljodfh.base.BaseActivity;
import com.deYang.app.ljodfh.base.Constances;
import com.deYang.app.ljodfh.base.SiChuanFocusApplication;
import com.deYang.app.ljodfh.beans.ADynamicsItem;
import com.deYang.app.ljodfh.beans.AFileItem;
import com.deYang.app.ljodfh.beans.AnchorList;
import com.deYang.app.ljodfh.beans.AnchorRecommendItem;
import com.deYang.app.ljodfh.beans.FProgramme;
import com.deYang.app.ljodfh.beans.Titles;
import com.deYang.app.ljodfh.http.AbsNetCallBack;
import com.deYang.app.ljodfh.http.NetUtils;
import com.deYang.app.ljodfh.ui.activities.AnchorCircleActivity;
import com.deYang.app.ljodfh.ui.activities.VideoPlayActivity;
import com.deYang.app.ljodfh.ui.adapter.AnchorHomePageAdapter;
import com.deYang.app.ljodfh.ui.util.IListShowData;
import com.deYang.app.ljodfh.ui.utils.SkipUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/11 0011.
 */
public class AnchorFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView {
    @BindView(R.id.fragment_anchor_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.anchor_list)
    protected RecyclerView anchor_list;
    @BindView(R.id.anchor_video_container)
    protected AbsoluteLayout videoContainer;
    private AnchorHomePageAdapter adapter;
    private LinearLayoutManager manger;
    private AnchorList item;
    private int otherHeight;
    private MotionEvent mCurrentMotion;

    private int dataVersion;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_anchor, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
//        anchor_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//            }
//
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                if (floatVideoUtils != null) {
//                    floatVideoUtils.recyclerScrolled(dx, dy);
//                }
//            }
//        });
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manger = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        anchor_list.setItemAnimator(new DefaultItemAnimator());
        anchor_list.setLayoutManager(manger);
        detail.setiScrollView(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SkipUtil.REQUEST_CODE_PLAY_BASE) {
            if (data != null || adapter != null) {
                int pos = data.getIntExtra(VideoPlayActivity.EXTRA_POS_ITEM, -1);
                if (pos >= 0) {
                    ADynamicsItem item = (ADynamicsItem) adapter.getItem(pos);
                    if (item == null) {
                        return;
                    }
                    if (resultCode == getActivity().RESULT_OK) {
                        item.setPlayedPos(0);
                    } else {
                        int playedPos = data.getIntExtra(VideoPlayActivity.EXTRA_POS, -1);
                        if (playedPos > 0) {
                            item.setPlayedPos(playedPos);
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onFragmentUnShowed(boolean isCallFromPause) {
        super.onFragmentUnShowed(isCallFromPause);
        if (floatVideoUtils != null) {
            floatVideoUtils.onPause();
        }
    }

    @Override
    public void onDestroyView() {
        if (floatVideoUtils != null) {
            anchor_list.removeOnScrollListener(floatVideoUtils.getRecyclerScrollListener());
        }
        super.onDestroyView();
    }

    @Override
    public boolean hasShowPlayer() {
        return floatVideoUtils != null && floatVideoUtils.isHasInited();
    }

    @Override
    public boolean onBackPressed() {
        if (floatVideoUtils != null && floatVideoUtils.onBackPress()) {
            actionToPortrait();
            return true;
        }
        return super.onBackPressed();
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        super.onFragmentShow(isFirst, isCallFromResume);
        if (isFirst) {
            refreshLayout.autoRefresh();
        } else {
            boolean b = ((SiChuanFocusApplication) getActivity().getApplication()).getDatasVersionManager().isVersionDiff(Constances.DATA_VERSION_ADYNAMIC, dataVersion);
            if (b){
                refreshLayout.autoRefresh();
            }
        }
        return true;
    }

    @Override
    public void onLoadMore() {

    }


    @Override
    public void onRefresh() {
        getAnchorPageList();

    }

    @Override
    public boolean getUserVisibleHint() {
        return super.getUserVisibleHint();
    }

    private void getAnchorPageList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            refreshLayout.refreshComplete();
            return;
        }
        NetUtils.getNetAdapter().getAnchorList(getOwnerName(), channelUrl, new AbsNetCallBack<AnchorList>(AnchorList.class) {

            private List<AnchorRecommendItem> recommendItemList;

            @Override
            public void onSuc(AnchorList anchorList) {
                if (anchorList != null) {
                    JLog.e("====anchor==" + anchorList.toString());
                    item = anchorList;
                    setAnchorData(anchorList, recommendItemList);
                }
            }

            @Override
            public AnchorList doInBackground(AnchorList anchorList) {
                if (anchorList != null && ListUtils.isListValued(anchorList.getAnchorNode())) {
                    if (recommendItemList == null) {
                        recommendItemList = new ArrayList<AnchorRecommendItem>();
                        List<FProgramme> list = anchorList.getAnchorNode();
                        AnchorRecommendItem ari = null;
                        int n = 0;
                        for (int i = 0; i < list.size(); i++) {
                            if (n == 0) {
                                if (ari != null) {
                                    recommendItemList.add(ari);
                                }
                                ari = new AnchorRecommendItem(list.get(i), null);
                                ari.setViewType(AnchorHomePageAdapter.VIEWTYPE_RECOMMEND);
                                n++;
                            } else {
                                ari.setProgramme2(list.get(i));
                                n = 0;
                            }
                        }
                        if (ari != null) {
                            recommendItemList.add(ari);
                        }
                    }
                }
                return super.doInBackground(anchorList);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
    }

    public void setAnchorData(AnchorList anchorData, List<AnchorRecommendItem> recommendList) {
        dataVersion=((SiChuanFocusApplication) getActivity().getApplication()).getDatasVersionManager().getVersion(Constances.DATA_VERSION_ADYNAMIC);
        ArrayList<IListShowData> list = new ArrayList<>();
        Titles titles = null;
        List<FProgramme> recommend = anchorData.getAnchorNode();
        List<ADynamicsItem> dynamics = anchorData.getAnchorDynamic();
        List<AFileItem> file = anchorData.getAnchorDoc();
        if (ListUtils.isListValued(recommendList)) {
            titles = new Titles();
            titles.setTitle(getString(R.string.anchor_recommend));
            titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLE);
            list.add(titles);
//            for (FProgramme program : recommend) {
//                program.setViewType(AnchorHomePageAdapter.VIEWTYPE_RECOMMEND);
//            }
            list.addAll(recommendList);
        }
        if (ListUtils.isListValued(dynamics)) {
            titles = new Titles();
            titles.setTitle(getString(R.string.anchor_dynamics));
            titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLES);
            list.add(titles);
            for (int i = 0; i < dynamics.size(); i++) {
                ADynamicsItem dynamicsItem = dynamics.get(i);
                dynamicsItem.setViewType(AnchorHomePageAdapter.VIEWTYPE_DYNAMICS);
//                dynamicsItem.setCoverImage("/sctv/1/image/public/201708/20170828112101_pex8ecr7nr.jpg");
//                dynamicsItem.setContentVideo("http://baobab.wdjcdn.com/1455969783448_5560_854x480.mp4");
                // dynamicsItem.setLastItem(i == dynamics.size() - 1);
            }
            list.addAll(dynamics);
        }
        if (ListUtils.isListValued(file)) {
            titles = new Titles();
            titles.setTitle(getString(R.string.anchor_file));
            titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLE);
            list.add(titles);
            for (AFileItem fileItem : file) {
                fileItem.setViewType(AnchorHomePageAdapter.VIEWTYPE_FILE);
            }
            list.addAll(file);
        }
        if (adapter == null) {
            adapter = new AnchorHomePageAdapter(getContext(), list).setItemInternalClick(circleOnClick);
            adapter.setPlayClick(playClick);
            anchor_list.setAdapter(adapter);
        } else {
            adapter.setData(list);
        }
    }

    private void playVideo(View img, String title) {
        int netType = NetModeUtil.GetNetype(getContext());
        if (initFloat(img, videoContainer, otherHeight)) {
//            bottomController.initInfo(liveInfo);
            anchor_list.addOnScrollListener(floatVideoUtils.getRecyclerScrollListener());

        }
//        floatVideoUtils.setLiving(false).play(img, contentVideoUrl);
        floatVideoUtils.play(img, contentVideoUrl, title, true);
//        playView=img;
//        if (netType == 1) {
//        } else {
//            showNetDialog();
//        }

    }

    OnItemInternalClick circleOnClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            Intent intent = new Intent(getContext(), AnchorCircleActivity.class);
            if (!TextUtils.isEmpty(item.getAnchorLoopEntry())) {
                intent.putExtra(BaseActivity.EX_HTML, item.getAnchorLoopEntry());
            }
            startActivity(intent);
        }
    };


    OnItemInternalClick playClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            itemClick(itemView, view, position);
//            playView = view;
//            playVideo(view, "");
        }
    };

    private void itemClick(View itemView, View view, int position) {
        ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(position);
        contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamics.getContentVideo());
        SkipUtil.skipToVideoPlay(this, contentVideoUrl, dynamics.getPlayedPos(), position);
    }

    public AnchorFragment setOtherHeight(int otherHeight) {
        this.otherHeight = otherHeight;
        return this;
    }


    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(anchor_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(anchor_list, 1);
    }

}
